﻿using LogionDemo.Common.UserEventArgs;
using LogionDemo.Controls;
using LogionDemo.Controls.Base;
using LogionDemo.Models;
using LogionDemo.Models.Enums;

namespace LogionDemo.Views
{
	public partial class MainForm : MainBaseForm
	{
		public MainForm()
		{
			InitializeComponent();
			Subscribe(new LoginStatusObserver());
			//首先实例化基类，然后才是衍生类，在实例化基类时，并没有+=事件。这里要注意。
			LoginStatusChangedEvent += MainForm_LoginStatusChanged;
			tslUserName.Text = LoginMessage;
		}

		private void btnOther_Click(object sender, EventArgs e) => NavigateSimple(new OtherUC(), pnlContent);

		private void btnPLC_Click(object sender, EventArgs e) => NavigateSimple(new PlcUC(), pnlContent);

		private void btnRole_Click(object sender, EventArgs e) => NavigateSimple(new RoleUC(this), pnlContent);

		private void MainForm_Load(object sender, EventArgs e)
		{
			UpdateUI();
		}

		private void MainForm_LoginStatusChanged(object? sender, LoginStatusChangedEventArgs e)
		{
			tslUserName.Text = LoginMessage;
			Publish(new LoginStatusChangedEventArgs(IsLoggedIn, UserToken!));
			UpdateUI();
		}

		private void NavigateSimple(UserControl userControl, Panel panel)
		{
			panel.Controls.Clear();
			panel.Controls.Add(userControl);
			userControl.Show();
		}

		private void tsBtnLogin_Click(object sender, EventArgs e)
		{
			Login();
			tslUserName.Text = LoginMessage;
		}

		private void tsBtnLoginOut_Click(object sender, EventArgs e)
		{
			var userToken = UserToken;
			Logout();
			tslUserName.Text = "已经注销";
		}

		private void UpdateUI()
		{
			//线程问题
			tsBtnLogin.Enabled = !IsLoggedIn;
			tsBtnLoginOut.Enabled = IsLoggedIn;
			btnRole.Enabled = UserToken != null && UserToken.Role == UserRole.Admin;
			btnPLC.Enabled = IsLoggedIn;
			btnOther.Enabled = IsLoggedIn;
		}
	}
}